package util

import (
	"bytes"
	"encoding/json"
	"errors"
	"gitee.com/liyunyi/log-app/internal/model"
	"github.com/gin-gonic/gin"
	"github.com/mitchellh/mapstructure"
	"net/http"
)

func ResponseHandle(w http.ResponseWriter, response *model.Response) {
	// 编码为 JSON
	jsonResponse, err := json.Marshal(response)
	if err != nil {
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
		return
	}

	// 设置响应头
	w.Header().Set("Content-Type", "application/json")

	// 发送响应
	w.WriteHeader(response.Status)
	_, _ = w.Write(jsonResponse)
}

// 自定义一个结构体，实现 gin.ResponseWriter interface
type ResponseWriter struct {
	gin.ResponseWriter
	B *bytes.Buffer
}

// 重写 Write([]byte) (int, error) 方法
func (w ResponseWriter) Write(b []byte) (int, error) {
	//向一个bytes.buffer中写一份数据来为获取body使用
	w.B.Write(b)
	//完成gin.Context.Writer.Write()原有功能
	return w.ResponseWriter.Write(b)
}

func GetParameterFromContext(ctx *gin.Context, model interface{}) error {
	if value, exists := ctx.Get("paramMap"); exists {
		err := mapstructure.WeakDecode(value, &model)
		return err
	}
	return errors.New("can not get parameter from context")
}
